package epam.com.classes;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import epam.com.enums.EnumTypeSentence;

public class Sentence {

	public String sentence;
	public int lenghtSentence;
	public int countWords;
	public EnumTypeSentence typeSentence;
	private static String regexPunctuation;
	private List<Word> words = new ArrayList<Word>();
	private static final Logger log = Logger
			.getLogger(Sentence.class.getName());
	private static Properties props = new Properties();

	public Sentence(String sentence) throws FileNotFoundException, IOException {
		this.sentence = sentence;
		lenghtSentence = sentence.length();
		loadPropertiesP();
		getTypeSentence();
		loadWords();
	}

	private static void loadPropertiesP() throws IOException {		
		props = new Properties();
		try {
			props.load(new FileInputStream("config.properties"));
			regexPunctuation = props.getProperty("regexPunctuation");
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}

	private void getTypeSentence() {
		char endChar = sentence.charAt(lenghtSentence - 1);
		switch (endChar) {
		case '.':
			typeSentence = EnumTypeSentence.DECLARATIVE;
			break;
		case '!':
			typeSentence = EnumTypeSentence.EXCLAMATORY;
			break;
		case '?':
			typeSentence = EnumTypeSentence.INTERROGATIVE;
			break;
		default:
			typeSentence = EnumTypeSentence.DECLARATIVE;
			break;
		}
	}

	private void loadWords() {
		String str = sentence.replaceAll(regexPunctuation, "");
		String tempWords[] = str.split(" ");
		words.clear();
		for (String thisword : tempWords) {
			words.add(new Word(thisword));
		}
		countWords = tempWords.length;
	}

	public void changeFirstAndLastWords() {
		if (countWords < 2) {
			log.warn("In the  sentence is  " + countWords + "  word");
			return;
		}
		Word firstWord = words.get(0);
		Word endWord = words.get(countWords - 1);
		String s = endWord.getWord();
		sentence = sentence.replaceFirst(firstWord.getWord(), endWord.setUpperFirstChar() );
		int poz = sentence.lastIndexOf(s);	
		sentence = sentence.substring(0, poz)+ firstWord.setLowerFirstChar()
				+ sentence.substring(poz + endWord.length());
		loadWords();
		log.info("CHANGE->" + sentence);
	}
}
